package com.yeeverse.api.demo.utils;/**
 * @Description:
 * @author kai.yang
 * @since 2020-11-02 10:45
 */

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * @Description:
 * @Author: kai.yang
 * @Date: 2020-11-02 10:45
 */
public class FileUtils {

    private static Logger logger = LoggerFactory.getLogger(FileUtils.class);


    public static String encodeStream(InputStream in) throws IOException {
        byte[] readStreamToByteArray = toByByteArray(in);
        return Base64.encodeBase64String(readStreamToByteArray);
    }

    public static InputStream decodeStream(String in) {
        byte[] decodeBase64 = Base64.decodeBase64(in);
        return new ByteArrayInputStream(decodeBase64);
    }


    public static String encodeFile(File file) throws IOException {
        byte[] readFileToByteArray = org.apache.commons.io.FileUtils.readFileToByteArray(file);
        return Base64.encodeBase64String(readFileToByteArray);
    }

    public static String encodeFile(String filePath) throws IOException {
        return encodeFile(new File(filePath));
    }

    public static void decodeFile(String codes, File file) throws IOException {
        byte[] decodeBase64 = Base64.decodeBase64(codes);
        org.apache.commons.io.FileUtils.writeByteArrayToFile(file, decodeBase64);
    }

    public static void decodeFile(String codes, String filePath) throws IOException {
        decodeFile(codes, new File(filePath));
    }

    private static byte[] toByByteArray(InputStream in) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 2];
        int n = 0;
        while (-1 != (n = in.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }

}
